﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using crmservice;

public partial class Nomination : System.Web.UI.Page
{
    private CrmService crm;

    protected void Page_Load(object sender, EventArgs e)
    {
        crm = CRMServiceFactory.CreateCRMService(ConfigurationManager.AppSettings.Get("CRMOrganizationName"));
        if (true) // CS 09/29/10 - changed this to always reload the boards lists b/c there's validation now.  !Page.IsPostBack)
        {
            Utilities.LoadStateDropDownList(crm, ref ddlState);
            Utilities.LoadStateDropDownList(crm, ref ddlEmployerState);
            Utilities.LoadEthnicityDropDownList(crm, ref ddlEthnicity);
            string Script = Utilities.BuildBoardJavascript(crm);
            ClientScript.RegisterStartupScript(this.GetType(), "OASYSScript", Script);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == false) return;

        try
        {
            oasys_nomination nom = new oasys_nomination();

            nom.oasys_nominatortilte = txtNominatorTitle.Text;
            nom.oasys_nominatorfirstname = txtNominatorFirstName.Text;
            nom.oasys_nominatormiddlename = txtNominatorMiddleName.Text;
            nom.oasys_nominatorlastname = txtNominatorLastName.Text;
            nom.oasys_nominatoremail = txtNominatorEmail.Text;
            nom.oasys_nominatorfullname = Utilities.BuildFullName(nom.oasys_nominatorfirstname, nom.oasys_nominatormiddlename, nom.oasys_nominatorlastname);

            nom.oasys_memberofnominatingorganization = Utilities.RadioButtonToPickList(radOrganizationNo, radOrganizationYes);
            nom.oasys_nominatingorganization = txtOrganization.Text;
            nom.oasys_positioninnominatingorganization = txtOrganizationPosition.Text;

            if (Request["lstBoards"] != null)
            {
                nom.oasys_boardstonominationsid = new Lookup();
                nom.oasys_boardstonominationsid.Value = new Guid(Request["lstBoards"]);
                ColumnSet cols = new ColumnSet();
                cols.Attributes = new string[] { "oasys_boardandcommissionbysecretariatid", "oasys_displayname", "oasys_name" };
                oasys_boardsandcommissionsmasterlist SelBoard = (oasys_boardsandcommissionsmasterlist)crm.Retrieve(EntityName.oasys_boardsandcommissionsmasterlist.ToString(), nom.oasys_boardstonominationsid.Value, cols);
                nom.oasys_secretariattonominationsid = SelBoard.oasys_boardandcommissionbysecretariatid;
                nom.oasys_secretariat = SelBoard.oasys_boardandcommissionbysecretariatid.name;
                nom.oasys_boarddisplayname = SelBoard.oasys_displayname;
                nom.oasys_boardshortname = SelBoard.oasys_name;
                nom.oasys_boardpreviousname = SelBoard.oasys_displayname;
            }
            nom.oasys_boardposition = txtPosition.Text;

            nom.oasys_nomineeotherexperiences = txtExperience.Text;
            nom.oasys_nomineefirstname = txtFirstName.Text;
            nom.oasys_nomineemiddlename = txtMiddleInitial.Text;
            nom.oasys_nomineelastname = txtLastName.Text;
            nom.oasys_name = Utilities.BuildFullName(nom.oasys_nomineefirstname, nom.oasys_nomineemiddlename, nom.oasys_nomineelastname);
            nom.oasys_nomineefullname = nom.oasys_name;

            nom.oasys_nomineestreetaddress = txtAddress.Text;
            nom.oasys_nomineecity = txtCity.Text;
            nom.oasys_nomineestate = ddlState.SelectedItem.Text;
            nom.oasys_nomineezipcode = txtZipCode.Text;
            nom.oasys_nomineehomephone = txtPrimaryPhone.Text;
            nom.oasys_nomineemobilephone = txtMobilePhone.Text;
            nom.oasys_nomineeworkphone = txtWorkPhone.Text;
            nom.oasys_nomineefaxphone = txtFaxNumber.Text;
            nom.oasys_nomineeemail = txtEmail.Text;

            nom.oasys_nomineeemployerfirm = txtEmployerName.Text;
            nom.oasys_nomineeemploymentposition = txtJobTitle.Text;
            //nom.oasys_nomineetypeofbusiness = txtEmployerServiceType.Text;
            nom.oasys_nomineebusinessstreetaddress = txtEmployerAddress.Text;
            nom.oasys_nomineebusinesscityaddress = txtEmployerCity.Text;
            nom.oasys_oasysnomineebusinessstate = ddlEmployerState.SelectedItem.Text;
            nom.oasys_nomineebusinesszipcode = txtEmployerZipCode.Text;

            nom.oasys_nomineesex = Utilities.RadioButtonToPickList(radGenderMale, radGenderFemale);
            nom.oasys_nomineedateofbirth = new CrmDateTime();
            nom.oasys_nomineedateofbirth.Value = txtDOB.Text;
            nom.oasys_nomineeplaceofbirth = txtPlaceOfBirth.Text;
            nom.oasys_nomineeethnicgroup = ddlEthnicity.SelectedItem.Text;
            nom.oasys_nomineeeducation = txtEducation.Text;

            Guid NomID = crm.Create(nom);

            if (NomID != null)
            {
                if (ResumeUploader.HasFile)
                {
                    UploadResume(NomID);
                }
            }


            Server.Transfer("~/NominationResult.aspx");
        }
        catch (Exception ex)
        {
            lblError.Text = string.Format("An error occurred while submitting the nomination: {0}", ex.Message + " " + ex.StackTrace);
        }
    }

    protected void vldBoards_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (Request["lstBoards"] != "0");
    }

    protected void vldResume_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string filename = ResumeUploader.FileName;
        args.IsValid = (filename.EndsWith(".docx", StringComparison.CurrentCultureIgnoreCase) || 
                        filename.EndsWith(".doc", StringComparison.CurrentCultureIgnoreCase) || 
                        filename.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase));
    }

    void UploadResume(Guid AppID)
    {
        string FilePath = Server.MapPath(string.Format("App_Data/{0}.{1}", AppID.ToString(), Path.GetExtension(ResumeUploader.FileName)));
        ResumeUploader.SaveAs(FilePath);
        
        if (File.Exists(FilePath))
        {
            annotation note = new annotation();
            note.notetext = "Resume uploaded with OASYS";
            note.subject = "Resume";
            note.objectid = new Lookup();
            note.objectid.type = "oasys_nomination";
            note.objectid.Value = AppID;
            note.objecttypecode = new EntityNameReference();
            note.objecttypecode.Value = "oasys_nomination";

            Guid NoteID = crm.Create(note);

            FileStream stream = File.OpenRead(FilePath);
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            stream.Close();

            string encodedData = System.Convert.ToBase64String(byteData);

            annotation updateNote = new annotation();
            updateNote.annotationid = new Key();
            updateNote.annotationid.Value = NoteID;
            updateNote.documentbody = encodedData;
            updateNote.filename = Path.GetFileName(FilePath);
            if (updateNote.filename.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase) )
                updateNote.mimetype = @"application/pdf";
            else
                updateNote.mimetype = @"application/msword";

            crm.Update(updateNote);
            crm.Dispose();

            File.Delete(FilePath);
        }
    }


    //protected void vldPhones_ServerValidate(object source, ServerValidateEventArgs args)
    //{
    //    bool phoneProvided = (txtPrimaryPhone.Text.Length > 0 || txtWorkPhone.Text.Length > 0 || txtMobilePhone.Text.Length > 0);
    //    args.IsValid = phoneProvided;
    //}
}
